﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.ComponentModel.DataAnnotations;

namespace ExpertSMS.Models
{
    public class Unit
    {
        public int UnitID { get; set; }
        [Display(Name="ชื่อหน่วย")]
        public string Name { get; set; }
        [Display(Name="ตัวคูณ")]
        public decimal ConvertingFactor { get; set; }

        [Display(Name = "สินค้า")]
        public int? ProductID { get; set; }
        [Display(Name = "หน่วยหลัก")]
        public int? ParentUnitID { get; set; }
        

        [ForeignKey("ParentUnitID")]
        public virtual Unit ParentUnit { get; set; }

        public virtual ICollection<Unit> ChildUnits { get; set; }
        public virtual Product Product { get; set; }

        public Unit()
        {
            ConvertingFactor = 1;
        }

        public virtual decimal ConvertingFactorToMainUnit
        {
            get
            {
                if (!this.ParentUnitID.HasValue)
                {
                    return this.ConvertingFactor;
                }
                else
                {
                    ExpertSMSContext context = new ExpertSMSContext();
                    return this.ConvertingFactor * context.Units.FirstOrDefault(x => x.UnitID == this.ParentUnitID.Value).ConvertingFactor;
                }
            }
        }
    }
}